<?php

namespace App\Services;

use App\Models\BooleanLogModel;
use App\Models\MemberModel;
use App\Utils\PriceUtis;

class MemberService
{
    private $model;

    public function __construct()
    {
        $this->model = new MemberModel();
    }

    public function getMemberInfoByNumber(string $number)
    {
        $info = $this->model->where([
            'number' => $number
        ])->first();
        return $info;
    }

    public function getMemberInfoById(int $id)
    {
        $info = $this->model->where([
            'id' => $id
        ])->first();
        return $info;
    }

    /**
     * 根据邀请人id获取团队列表
     * @param int $uid
     */
    public function getMemberListByInvitationUid(int $uid)
    {
        $list = $this->model->where([
            'invitation_uid' => $uid
        ])->get();
        foreach ($list as &$item) {
            if (!$item->nick_name) {
                $item->nick_name = '微信用户';
            }
        }
        return $list;
    }

    public function getMemberInfoByInvitationCode(string $invitationCode)
    {
        $info = $this->model->where([
            'invitation_code' => $invitationCode
        ])->first();
        return $info;
    }

    public function passEncode($password)
    {
        return password_hash($password, PASSWORD_DEFAULT);
    }

    public function passCheck($password, $hash)
    {
        return password_verify($password, $hash);
    }

    public function getOpenid(string $code)
    {
        $appid = env('WX_APP_ID');
        $secret = env('WX_APP_SECRET');
        // 获取openid连接
        $weixin_url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $weixin_data = file_get_contents($weixin_url);
        $result = json_decode($weixin_data, true);
        if (!isset($result['openid']) || empty($result)) {
            return [false, ''];
        }
        return [true, $result['openid']];
    }

    /**
     * 修改账户余额
     * @param int $type 操作类型：1增加，2减少
     * @param int $userId 用户id
     * @param int $money 操作金额：元
     * @param int $relationId 关联提现记录id
     */
    public function editBoolean(int $type, int $userId, int $money, $relationId = 0)
    {
        $userInfo = $this->getMemberInfoById($userId);
        $moneyTofen = PriceUtis::toFen($money);
        if ($type == 1) {
            $userInfo->boolean += $moneyTofen;
        } else {
            $userInfo->boolean -= $moneyTofen;
        }
        $res = $userInfo->save();
        if ($res) {
            $booleanLog = new BooleanLogModel();
            $booleanLog->user_id = $userId;
            $booleanLog->type = $type;
            $booleanLog->type = $type;
            $booleanLog->relation_id = $relationId;
            $booleanLog->boolean_num = $moneyTofen;
            $booleanLog->save();
        }
    }
}
